<template>
  <header class="header">
    <!--    {{ title }}-->
    <view class="header-btn">
      <!--      <block-->
      <!--        v-if="-->
      <!--          pageData.sign === INDENTIFICATION.PAGE_MODAL ||-->
      <!--          pageData.sign === INDENTIFICATION.PAGE_FORM_MODAL-->
      <!--        "-->
      <!--      >-->
      <!--        <u-button-->
      <!--          v-if="isPageModified"-->
      <!--          type="primary"-->
      <!--          @click="isShowPreviewBefore = true"-->
      <!--          size="mini"-->
      <!--          style="width: 40px; margin-right: 20px"-->
      <!--          >预览</u-button-->
      <!--        >-->
      <!--        <u-button-->
      <!--          v-else-->
      <!--          type="primary"-->
      <!--          @click="onClickPreview"-->
      <!--          size="mini"-->
      <!--          style="width: 40px; margin-right: 20px"-->
      <!--          >预览</u-button-->
      <!--        >-->
      <!--      </block>-->

      <u-button
        type="primary"
        @click="onClickSavePage"
        size="mini"
        style="width: 40px; margin-right: 20px"
        :color="$theme.themeColor.primary"
        >保存</u-button
      >
      <!--      <block>-->
      <!--        <u-button-->
      <!--          v-if="-->
      <!--            (pageData.sign === INDENTIFICATION.PAGE_MODAL ||-->
      <!--              pageData.sign === INDENTIFICATION.PAGE_FORM_MODAL) &&-->
      <!--            op === OPERATION_TYPE.EDIT-->
      <!--          "-->
      <!--          type="primary"-->
      <!--          @click="onClickChangePageStatus"-->
      <!--          size="mini"-->
      <!--          style="width: 40px; margin-right: 20px"-->
      <!--          >{{ status === PAGE_STATUS.ON ? "禁用" : "启用" }}</u-button-->
      <!--        >-->
      <!--        <u-button-->
      <!--          v-else-->
      <!--          type="primary"-->
      <!--          @click="onClickChangeLocalPageStatus"-->
      <!--          size="mini"-->
      <!--          style="width: 40px; margin-right: 20px"-->
      <!--          >{{ status === PAGE_STATUS.ON ? "禁用" : "启用" }}</u-button-->
      <!--        >-->
      <!--      </block>-->
      <u-button
        type="primary"
        plain
        @click="onClickBack"
        size="mini"
        :color="$theme.themeColor.primary"
        style="width: 40px; margin-right: 20px"
        >返回</u-button
      ></view
    >

    <u-popup
      :show="isShowPreviewBefore"
      @close="isShowPreviewBefore = false"
      mode="center"
      round="8"
    >
      <div class="popup-preview-before">
        <div class="popup-preview-before-close">
          <div>提示</div>
          <u-icon
            name="close"
            class="close-circle"
            size="20"
            @click="isShowPreviewBefore = false"
          />
        </div>
        <div class="popup-preview-before-content">
          <u-icon
            name="info-circle-fill"
            :color="$theme.themeColor.primary"
            style="margin-right: 5px"
            size="18"
          />
          有修改未保存,是否先保存再预览
        </div>
        <div class="popup-preview-before-footer">
          <u-button
            type="primary"
            plain
            @click="isShowPreviewBefore = false"
            size="small"
            >取消</u-button
          >
          <u-button type="primary" @click="onClickSaveAndPreview" size="small"
            >保存并预览</u-button
          >
        </div>
      </div>
    </u-popup>

    <!--    <u-modal-->
    <!--      :show="isShowPreviewBefore"-->
    <!--      title="提示"-->
    <!--      @confirm="onClickSaveAndPreview"-->
    <!--      @cancel="isShowPreviewBefore = false"-->
    <!--      @close="isShowPreviewBefore = false"-->
    <!--      :showCancelButton="true"-->
    <!--    >-->
    <!--      是否先保存再预览-->
    <!--    </u-modal>-->
  </header>
</template>

<script>
import {
  saveModule,
  savePage,
  updateModule,
  updatePage,
  updateStatus,
} from "@/service/api/lowcode";
import {
  INDENTIFICATION,
  MODULE_TYPE,
  OPERATION_TYPE,
  PAGE_STATUS,
  COMPREIFX,
  PAGE_TYPE,
} from "@/const/widget";
import { API_SUCCESS_CODES } from "@/const/application/service";

export default {
  name: "index",
  computed: {
    op() {
      return this.$store.state.page.operationStatus;
    },
    pageData() {
      return this.$store.state.page.page;
    },
    storeShotCover() {
      return this.$store.state.page.shotCover;
    },
    isPageModified() {
      return this.$store.state.page.isPageModified;
    },
    status() {
      return this.$store.state.page.status;
    },
    // title() {
    //   const { sign, op } = this.$route.query;
    //   return (
    //     (op === OPERATION_TYPE.ADD ? "新增" : "编辑") +
    //     (sign === INDENTIFICATION.PAGE_MODAL
    //       ? INDENTIFICATION_TEXT.PAGE_MODAL
    //       : sign === INDENTIFICATION.PAGE_FORM_MODAL
    //       ? INDENTIFICATION_TEXT.PAGE_FORM_MODAL
    //       : sign === INDENTIFICATION.DESC_MODAL
    //       ? INDENTIFICATION_TEXT.DESC_MODAL
    //       : INDENTIFICATION_TEXT.FORM_MODAL)
    //   );
    // },
    apiOptions() {
      const { sign } = this.$route.query;
      let options = {
        save: null,
        update: null,
      };
      const signs = [
        INDENTIFICATION.PAGE_MODAL,
        INDENTIFICATION.PAGE_FORM_MODAL,
        INDENTIFICATION.USER_CENTER_MODAL,
      ];
      options.save = signs.includes(sign) ? savePage : saveModule;
      options.update = signs.includes(sign) ? updatePage : updateModule;
      return options;
    },
  },
  data() {
    return {
      OPERATION_TYPE,
      INDENTIFICATION,
      PAGE_STATUS,
      isShowPreviewBefore: false,
      isBack: false,
    };
  },
  methods: {
    handleSavePage(isBack = false) {
      this.isBack = isBack;
      return new Promise((resolve, reject) => {
        const { sign } = this.$route.query;
        const { op } = this;
        const api =
          op === OPERATION_TYPE.ADD || op === OPERATION_TYPE.COPY
            ? this.apiOptions.save
            : this.apiOptions.update;
        const returnTxt =
          op === OPERATION_TYPE.ADD || op === OPERATION_TYPE.COPY
            ? "新建"
            : "保存";
        const pageData = JSON.parse(JSON.stringify(this.pageData));
        pageData.attribute.shotCover = this.storeShotCover;
        //---前置判断 start---
        let isHasEmpty = false;
        let isEmptySubmitTitle = false;
        let isHasCusFormSubmitButton = false;
        pageData.items.forEach((item) => {
          if (
            item.sign &&
            item.sign === INDENTIFICATION.CUS_FORM &&
            item.attribute &&
            item.attribute.hasOwnProperty("title")
          ) {
            if (!item.attribute.title) {
              isHasEmpty = true;
            }
          }
          if (item.type === `${COMPREIFX}submit-button`) {
            isHasCusFormSubmitButton = true;
            if (!item?.attribute?.text.trim()) {
              isEmptySubmitTitle = true;
            }
          }
        });
        if (!pageData.attribute.title) {
          const tips =
            sign === INDENTIFICATION.PAGE_MODAL ||
            sign === INDENTIFICATION.PAGE_FORM_MODAL
              ? "页面标题"
              : "模块名称";
          return this.$showMessage({
            op: "message",
            type: "error",
            content: "请输入" + tips,
          });
          // return uni.showToast({ title: tips, icon: "none" });
        }
        if (isHasEmpty && pageData.sign === INDENTIFICATION.FORM_MODAL) {
          return this.$showMessage({
            op: "message",
            type: "warning",
            content: "有组件标题为空，请完善~",
          });
        }

        if (
          pageData.sign === INDENTIFICATION.FORM_MODAL &&
          !isHasCusFormSubmitButton
        ) {
          return this.$showMessage({
            op: "message",
            type: "warning",
            content: "请添加提交按钮",
          });
        }
        if (
          pageData.sign === INDENTIFICATION.FORM_MODAL &&
          isEmptySubmitTitle
        ) {
          return this.$showMessage({
            op: "message",
            type: "warning",
            content: "请输入按钮文字",
          });
        }

        // if (!pageData.attribute.desc) {
        //   return uni.showToast({ title: "请输入描述" });
        // }
        //---前置判断 end---
        //当是附带api信息的组件的时候，data需要清空
        pageData?.items?.forEach((v) => {
          if (v.attribute && v.attribute.hasOwnProperty("api")) {
            v.attribute.data = {};
          }
        });
        let params = {
          pageJson: pageData,
          title: pageData.attribute.title,
          desc: pageData.attribute.desc,
          pageType: PAGE_TYPE[pageData.sign],
        };
        /*---参数变更 新增/编辑---*/
        //编辑的时候，id
        if (op === OPERATION_TYPE.EDIT) {
          params.id = pageData.page_id;
        } else {
          //新增/复制的时候，改变状态
          params.status = this.status;
        }
        //模块的时候，moduleType的标识
        if (
          sign === INDENTIFICATION.DESC_MODAL ||
          sign === INDENTIFICATION.FORM_MODAL
        ) {
          params.moduleType =
            sign === INDENTIFICATION.DESC_MODAL
              ? MODULE_TYPE.DESC_MODAL
              : MODULE_TYPE.FORM_MODAL;
          params.moduleName = params.title;
          params.moduleJson = params.pageJson;
        }
        console.log("保存的数据", params, pageData.sign);
        api(params)
          .then((res) => {
            if (res) {
              const { pageJson, moduleJson } = res;
              const json = pageJson || moduleJson;
              const page = JSON.parse(json);
              this.$store.dispatch("page/setPageJson", page);
              this.$store.dispatch("page/changePageModifiedStatus", false);
              this.$store.dispatch(
                "page/setEditConfigComActiveId",
                page.items[0]?.id
              );
              if (op === OPERATION_TYPE.ADD || op === OPERATION_TYPE.COPY) {
                this.$store.dispatch(
                  "page/setOperationStatus",
                  OPERATION_TYPE.EDIT
                );
              }
              this.$showMessage({
                op: "message",
                type: "success",
                content: returnTxt + "成功",
              });
              resolve();
              //平台返回上一层
            } else {
              this.$showMessage({
                op: "message",
                type: "success",
                content: returnTxt + "失败",
              });
              reject();
            }
          })
          .catch(() => {
            this.$showMessage({
              op: "message",
              type: "success",
              content: returnTxt + "失败",
            });
            reject();
          });
      });
    },
    onClickBack() {
      window.parent.postMessage(
        {
          sign: "backRouter",
        },
        "*"
      );
    },
    onClickSavePage() {
      this.handleSavePage(true).then(() => {
        this.handleEmitShotCover();
      });
    },
    onClickSaveAndPreview() {
      this.handleSavePage(false).then(() => {
        this.handleEmitShotCover();
        this.onClickPreview();
      });
    },
    handleEmitShotCover() {
      this.$emit("shotCover");
    },
    async handleShotCoverNextSavePage() {
      const { sign } = this.$route.query;
      const { op } = this;
      const api =
        op === OPERATION_TYPE.ADD || op === OPERATION_TYPE.COPY
          ? this.apiOptions.save
          : this.apiOptions.update;
      const pageData = JSON.parse(JSON.stringify(this.pageData));
      pageData.attribute.shotCover = this.storeShotCover;
      //当是附带api信息的组件的时候，data需要清空
      pageData?.items?.forEach((v) => {
        if (v.attribute && v.attribute.hasOwnProperty("api")) {
          v.attribute.data = {};
        }
      });
      console.log("页面数据", pageData);
      let params = {
        pageJson: pageData,
        title: pageData.attribute.title,
        desc: pageData.attribute.desc,
        pageType: PAGE_TYPE[pageData.sign],
      };
      /*---参数变更 新增/编辑---*/
      //编辑的时候，id
      if (op === OPERATION_TYPE.EDIT) {
        params.id = pageData.page_id;
      } else {
        //新增/复制的时候，改变状态
        params.status = this.status;
      }
      //模块的时候，moduleType的标识
      if (
        sign === INDENTIFICATION.DESC_MODAL ||
        sign === INDENTIFICATION.FORM_MODAL
      ) {
        params.moduleType =
          sign === INDENTIFICATION.DESC_MODAL
            ? MODULE_TYPE.DESC_MODAL
            : MODULE_TYPE.FORM_MODAL;
        params.moduleName = params.title;
        params.moduleJson = params.pageJson;
      }
      await api(params).then(() => {
        if (this.isBack) {
          this.onClickBack();
        }
      });
    },
    onClickPreview() {
      this.isShowPreviewBefore = false;
      this.$store.dispatch("page/setPagePreview", true);
    },
    onClickChangeLocalPageStatus() {
      const status =
        this.status === PAGE_STATUS.ON ? PAGE_STATUS.OFF : PAGE_STATUS.ON;
      this.$store.dispatch("page/setPageStatus", status);
    },
    async onClickChangePageStatus() {
      const params = {
        id: this.pageData.page_id,
        status:
          this.status === PAGE_STATUS.ON ? PAGE_STATUS.OFF : PAGE_STATUS.ON,
      };
      const { code, msg } = await updateStatus(params);
      await this.$showMessage({
        op: "message",
        type: API_SUCCESS_CODES.includes(code) ? "success" : "error",
        content: API_SUCCESS_CODES.includes(code) ? "更新成功" : msg,
      });
      if (API_SUCCESS_CODES.includes(code)) {
        await this.$store.dispatch("page/setPageStatus", params.status);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.header {
  display: flex;
  position: relative;
  padding: 20px 13.5px;
  background-color: #fcf6eb;
  align-items: center;
  &-btn {
    position: absolute;
    right: 0;
    display: flex;
  }
}
.popup-preview-before {
  padding: 10px 20px;
  border-radius: 8px;
  width: 375px;
  font-size: 16px;
  &-close {
    width: 100%;
    display: flex;
    position: relative;
    align-items: center;
    .close-circle {
      position: absolute;
      right: 0;
    }
  }
  &-content {
    display: flex;
    align-items: center;
    margin: 10px 0;
    font-size: 16px;
  }
  &-footer {
    display: flex;
    align-items: center;
    .u-button {
      margin-right: 10px;
    }
  }
}
</style>
